// pages/glaze/content/index.js

const app = getApp();
import fetch from '../../../api/recipe'
import {
  GLAZE,
  hasErr,
  inputValidHandle
} from '../../../utils/valid'

const form = {
  },
  form2 = {
    glazeFlowRate: {
      name: '1',
      type: '釉浆流速',
      value: '',
      err: '',
      desc: GLAZE['glazeFlowRate'].unit
    },
    glazeRatio: {
      name: '2',
      type: '釉浆比重',
      value: '',
      err: '',
      desc: GLAZE['glazeRatio'].unit
    },
    glazingAmount: {
      name: '3',
      type: '施釉量',
      value: '',
      err: '',
      desc: GLAZE['glazingAmount'].unit
    },
    screenMesh: {
      name: '5',
      type: '筛网目数',
      value: '',
      err: '',
      desc: GLAZE['screenMesh'].unit
    },
    ballGrindingFineness: {
      name: '9',
      type: '球磨细度',
      value: '',
      err: '',
      desc: GLAZE['ballGrindingFineness'].unit
    }
  }
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    item: {
      type: Object,
      value: {},
      observer(data) {
        this.initData(data)
      }
    },
    collectionId: {
      type: Number,
      value: 0
    },
    factorList: {
      type: Array,
      value: [],
      observer(data){
 
        this.setData({
          columnsList: data
        })
      }
    },
    selectFactorList: {
      type: Array,
      value: [],
      observer(data){
        this.setData({
          columns: data
        })
      }
    },
    idx: {
      type: Number,
      value: 0
    },
    disabled: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    form,
    glazeId: '',
    fields: Object.keys(form),
    form2,
    fields2: Object.keys(form2),
    show: false,
    showTips: false,
    /**配方 */
    columnsList: [],
    columnsValue: {},
    columns: [],
 
    /**已选择配方列表 */
    list: [],
    /**上半部分,选择原料后 */
 
    selectItem: {},
    recordState: app.globalData.editState,
    refreshLoading: false,
    isRoot: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onAddPFCancel() {
      this.setData({
        showPF: false
      })
    },

    toEdit(event) {
      const id = event.currentTarget.dataset.value;
      wx.navigateTo({
        url: '../../pages/recipe-edit/index?id=' + id + '&param=' + this.properties.collectionId,
      })
    },

    /**处理小数点 */
    format(data) {
      if (data) {
        return parseFloat(data).toFixed(2);
      }
      return 0
    },
    /**
     * 填充数据
     */
    async initData(data) {
        const f2 = {
          ...this.data.form2
        };
        let item = this.data.columnsList.find(it => {
          return it.id === data.recipeId
        });
      for (let it of this.data.fields2) {
        f2[it].value =  data[it]
      }
      // 如果此时配方被挂起的话，那么已发布的列表中便查找不到，此时需要从配方库里查找
     if(data?.recipeId && !item) {
        await (function(){
          return new Promise(resolve=>{
            fetch.recipeId(data.recipeId, res=>{
              item = res;
              resolve();
            })
          })
        })()
     }
      this.setData({
        form2: f2,
        selectItem: item || {},
        columnsValue: {
          text: item?.name,
          value: item?.id
        }
      })

    },
   
 
    /**
     * 添加配方的结果
     */
    addPFResult(res) {
      this.onClose();
      this.fetchRecipeList();
        selectItem = res;
      this.setData({
        selectItem
      })
    },
    /**
     * 添加配方
     */
    toAddPF() {
      wx.navigateTo({
        url: '../recipe/index?glaze=true&id=' + this.data.id,
      })
    },

    /**
     * 配方
     */
    showPicker() {
      this.setData({
        show: true
      })
    },

    /**
     * 保存操作
     * @param {any}
     */
    onChange(event) {
      // if (!(this.data.selectItem && this.data.selectItem.id)) {
      //   wx.showToast({
      //     title: '未选择配方！',
      //     icon: 'error'
      //   })
      //   return
      // }
      if (hasErr(this.data.form2)) {
        wx.showToast({
          title: '存在不合理的数值',
          icon: 'none'
        })
        return
      }
      const value = event.detail,
      key = event.currentTarget.dataset.key;
 
      const d = Object.assign({
      }, {
        [key]:value
      }, {
        recipeId: this.data.selectItem.id
      } )
       this.triggerEvent('change', [d,this.properties.idx]);
    },

    // /**
    //  * 化学成分弹窗开启
    //  */
    // chemicalOpenHandle(event) {
    //   const obj = this.data.columnsList.find(it => {
    //     return it.id === event.currentTarget.dataset.value
    //   });
    //   this.setData({
    //     chemicalShow: true,
    //     data: obj
    //   })
    //   this.setDataSource(obj?.recipeCombination, obj?.recipeOperationData)
    // },
    // /**
    //  * 化学成分弹窗关闭
    //  */
    // chemicalCloseHandle() {
    //   this.setData({
    //     chemicalShow: false
    //   })
    //   this.fetchData();
    // },
    /**配方 */
    onClose() {
      this.setData({
        show: false
      })
    },
    onRemove(){
       wx.showModal({
         content: '确定要移除此釉料吗？',
         success: res=>{
           if(res.confirm){
             this.triggerEvent('remove', this.properties.idx);
 
           }
         }
       })
    },
    pickerChangeHandle(e) {
      this.onClose();
      const  
        selectItem = this.data.columnsList.find(item => item.id === e.detail.value.value);
      this.setData({
        selectItem
      })
      this.triggerEvent('change', [{
        recipeId: selectItem.id
      },this.properties.idx]);
    },
    onInput(event) {
      const key = event.currentTarget.dataset.key,
        value = event.detail,
        form = this.data.form2;
     
      const target = GLAZE[key];
      let valid = true;
      if (inputValidHandle(value, GLAZE, key) === false) {
        form[key]['err'] = '数值不正确：' + target.desc;
        valid = false;
      } else {
        form[key]['err'] = '';
        valid = true;
      }
      form[key]['value'] = String(value);
      this.setData({
        form2: form
      })
      const d = Object.assign({
      }, {
        [key]:value,
        valid
      }, {
        recipeId: this.data.selectItem.id
      } )
       this.triggerEvent('change', [d,this.properties.idx]);
    },
    /**
     * 设置页面初始数据
     */
    setValues({
      detail
    }) {
      this.setData({
        columnsValue: detail.value
      })
    }
  }
})